<template>
  <div class="basic-content">
    <el-descriptions title="商户基本信息" />
    <el-form
      ref="ruleFormRef"
      label-position="top"
      :model="ruleForm"
      :rules="rules"
      class="basic-form"
      label-width="auto"
    >
      <el-form-item prop="license" class="upload-item">
        <el-upload
          class="upload-demo"
          drag
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-change="handleAvatarChange"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :limit="1"
          accept="image/png, image/jpeg, image/jpg"
          multiple
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <div v-else>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              <el-text size="large" type="primary"
                >*营业执照（三证合一）</el-text
              >
              <el-text size="small"
                >支持 JPG, PNG格式，文件大小不超过 5MB</el-text
              >
            </div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="企业名称" prop="companyName" disabled>
        <el-input v-model="ruleForm.companyName" placeholder="请输入企业名称" />
      </el-form-item>

      <el-form-item label="社会统一信用代码" prop="creditCode" disabled>
        <el-input
          v-model="ruleForm.creditCode"
          placeholder="请输入社会统一信用代码"
        />
      </el-form-item>

      <el-form-item label="企业简称" prop="companyShortName" disabled>
        <el-input
          v-model="ruleForm.companyShortName"
          placeholder="请输入企业简称"
        />
      </el-form-item>

      <el-form-item label="商户属性" prop="merchantType">
        <el-select v-model="ruleForm.merchantType" placeholder="请选择商户属性">
          <el-option label="企业" value="1" />
          <el-option label="小微企业" value="2" />
          <el-option label="个体工商户" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="营业执照有效期" prop="validity" disabled>
        <el-input
          v-model="ruleForm.validity"
          placeholder="请输入营业执照有效期"
        />
      </el-form-item>
      <el-form-item label="类目/行业分类" prop="industryType">
        <el-select-v2
          v-model="ruleForm.industryType"
          placeholder="请选择类目/行业分类"
          :options="options"
        />
      </el-form-item>

      <el-form-item label="注册资金" prop="capita">
        <el-input v-model="ruleForm.capita" placeholder="请输入注册资金" />
      </el-form-item>

      <el-form-item label="受益所有人" prop="beneficiary">
        <el-input
          v-model="ruleForm.beneficiary"
          placeholder="请输入受益所有人"
        />
      </el-form-item>

      <el-form-item label="企业网站/APP/公众号/小程序" prop="website">
        <el-input
          v-model="ruleForm.website"
          placeholder="请输入企业网站/APP/公众号/小程序"
        />
      </el-form-item>

      <el-form-item label="经营地址" prop="address">
        <el-input
          v-model="ruleForm.address"
          type="textarea"
          placeholder="请输入经营地址"
        />
      </el-form-item>

      <el-form-item label="经营范围描述" prop="busScope">
        <el-input
          v-model="ruleForm.busScope"
          type="textarea"
          placeholder="请输入经营范围描述"
        />
      </el-form-item>

      <!-- <el-form-item label="Activity time" required>
        <el-col :span="11">
          <el-form-item prop="date1">
            <el-date-picker
              v-model="ruleForm.date1"
              type="date"
              aria-label="Pick a date"
              placeholder="Pick a date"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="text-center" :span="2">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="date2">
            <el-time-picker
              v-model="ruleForm.date2"
              aria-label="Pick a time"
              placeholder="Pick a time"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item> -->
      <!-- <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          Create
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item> -->
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { UploadFilled } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";
import { message } from "@/utils/message";
interface RuleForm {
  companyName: string;
  creditCode: string;
  companyShortName: string;
  merchantType: string;
  validity: string;
  address: string;
  industryType: string;
  capita: string;
  beneficiary: string;
  website: string;
  busScope: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  companyName: "",
  creditCode: "",
  companyShortName: "",
  merchantType: "",
  validity: "",
  address: "",
  industryType: "",
  capita: "",
  beneficiary: "",
  website: "",
  busScope: ""
});
const imageUrl = ref("");
const options = reactive([
  { label: "服装鞋帽", value: 1 },
  { label: "电子产品", value: 2 },
  { label: "美妆", value: 3 },
  { label: "食品饮料", value: 4 },
  { label: "母婴家居", value: 5 }
]);

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<RuleForm>>({
  companyName: [
    { required: true, message: "请输入企业名称", trigger: "blur" },
    { min: 1, max: 100, message: "企业名称不得超过100个字符", trigger: "blur" }
  ],
  creditCode: [
    { required: true, message: "社会统一信用代码", trigger: "blur" },
    {
      min: 1,
      max: 18,
      message: "社会统一信用代码不得超过18个字符",
      trigger: "blur"
    }
  ],
  companyShortName: [
    { required: true, message: "请输入企业简称", trigger: "blur" },
    { min: 1, max: 50, message: "企业简称不得超过100个字符", trigger: "blur" }
  ],
  merchantType: [
    { required: true, message: "请选择商户属性", trigger: "change" }
  ],
  validity: [
    { required: true, message: "请输入营业执照有效期", trigger: "blur" }
  ],
  address: [
    { required: true, message: "请输入经营地址", trigger: "blur" },
    { min: 1, max: 200, message: "经营地址不得超过200个字符", trigger: "blur" }
  ],

  industryType: [
    { required: true, message: "请选择类目/行业分类", trigger: "change" }
  ],

  capita: [
    { required: true, message: "请输入注册资金", trigger: "blur" },
    { min: 1, max: 11, message: "不得超过11个字符", trigger: "blur" }
  ],

  beneficiary: [
    { required: true, message: "请输入受益所有人", trigger: "blur" },
    { min: 1, max: 50, message: "不得超过50个字符", trigger: "blur" }
  ],

  website: [
    {
      required: true,
      message: "请输入企业网站/APP/公众号/小程序",
      trigger: "blur"
    },
    { min: 1, max: 200, message: "不得超过200个字符", trigger: "blur" }
  ],
  busScope: [
    { required: true, message: "请输入经营范围描述", trigger: "blur" },
    { min: 1, max: 500, message: "不得超过500个字符", trigger: "blur" }
  ]
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // 优先使用 raw 文件，如果没有则使用 url
  if (uploadFile.raw) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
  } else if (uploadFile.url) {
    imageUrl.value = uploadFile.url;
  }
};

const handleAvatarChange: UploadProps["onChange"] = (response, uploadFile) => {
  // 优先使用 raw 文件，如果没有则使用 url
  if (uploadFile.raw) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
  } else if (uploadFile.url) {
    imageUrl.value = uploadFile.url;
  }
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  console.log("beforeUpload triggered:", rawFile);

  const fileType = ["image/png", "image/jpeg", "image/jpg"];
  if (!fileType.includes(rawFile.type)) {
    message("上传的图片只能是 JPG, PNG, JPEG格式", { type: "warning" });
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    message("上传的图片必须小于5M", { type: "warning" });
    return false;
  }
  // 直接在这里创建 URL，确保有文件对象
  imageUrl.value = URL.createObjectURL(rawFile);
  return true;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style lang="scss" scoped>
.basic-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .el-form-item {
    width: 48%;
    margin-bottom: 20px;
  }
  .upload-item {
    width: 100%;
  }
  .upload-demo {
    width: 48%;
    .el-upload__text {
      display: flex;
      flex-direction: column;
    }
    .avatar {
      height: 100px;
    }
  }
}
</style>
